/*
* File: logfile.cpp
* Version: 1.0
* Last modified on 2014-03-18 15:00
* Contributors : Nicklas Wallman (s131448), Olof Ivarsson(s132046), Oscar Ernstsson(s132952), Oscar Pehrson(s131469), Martin Jakobsson(s133082)
*/

#include <stdio.h>
#include <time.h>
#include "logfile.h"
#include "config.h"
#include <string.h>
#include <cstdlib>

static char *getDate();
static char *readFile(FILE *f);

extern configT srvConfig;

#define INITIAL_MEM_SIZE 512

/*int main ()
{
	
	saveLogfile("localhost","GET /apache_pb.gif HTTP/1.0",200,4000);


	return(0);
}
*/


/*
* Function: *readFile
* Usage: file = readFile(file);
* -----------------
* This function returns a file as a string.
*/
static char *readFile(FILE *f)
{
	char *buf, *tmpbuf, ch;
	int bufsize, c;

	c = 0;
	bufsize = INITIAL_MEM_SIZE;
	buf = (char*) malloc(bufsize + 1);

	if (buf == NULL)
	{
		return NULL;
	}

	while ( (ch = fgetc(f)) != EOF )
	{
		if (bufsize == c)
		{
			// realloc mem
			bufsize *= 2;
			tmpbuf = (char *) malloc(bufsize + 1);
			if (tmpbuf == NULL)
			{
				return NULL;
			}
			memcpy(tmpbuf, buf, bufsize);
			free(buf);
			buf = tmpbuf;
		}

		buf[c] = ch;
		c++; // 1337
	}

	// If empty, mem allocation was in vain. Deallocate.
	if (c == 0 && ch == EOF)
	{
		free(buf);
		return NULL;
	}

	buf[c++] = '\0';
	return buf;
}
/*
* Function: *getLogFile
* Usage: logfile = getLogFile();
* -----------------
* This function returns the logfile
*/
char *getLogFile(void)
{
	FILE *f;
	char *data;

	if ( (f = fopen(srvConfig.logPath, "r")) == NULL) 
	{
		return NULL;
	}

	data = readFile(f);
	return data;
}

/*
* Function: saveLogFile
* Usage: saveLogfile(hostname,reqDate,command,request,protocol,httpstatus,size);
* -----------------
* This function saves the logfile
*/
void saveLogfile(char *hostname,char *reqDate, char *cmd,char *req,char *protocol,int httpStatus,int size)
{
	FILE *logfile;
	logfile = fopen(srvConfig.logPath, "a");

	if (logfile != NULL)
	{
		fprintf(logfile, "%s %s \"%s %s %s\" %d %d\r\n", hostname, reqDate, cmd, req, protocol, httpStatus, size);
		fclose(logfile);
	}
	else
	{
		printf("Could not open logfile!\n");
	}
}

